#include "Queue.h"

Node* NodeCreate(TreeNode* data) {
    Node* newNode = MALLOC(Node, 1);
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

Queue* QueueInit() {
    Queue* queue = MALLOC(Queue, 1);
    queue->front = queue->rear = NULL;
    return queue;
}

void Enqueue(Queue* queue, TreeNode* data) {
    assert(queue);
    Node* newNode = NodeCreate(data);
    if (QueueEmpty(queue)) {
        queue->front = queue->rear = newNode;
    } else {
        queue->rear->next = newNode;
        queue->rear = newNode;
    }
}

TreeNode* Dequeue(Queue* queue) {
    assert(queue);
    if (QueueEmpty(queue)) {
        return NULL;
    }

    TreeNode* ret = queue->front->data;
    Node* temp = queue->front;
    queue->front = queue->front->next;
    if (QueueEmpty(queue)) {
        queue->rear = NULL;
    }
    free(temp);
    return ret;

}

void QueueDestroy(Queue* queue) {
    assert(queue);
    while (!QueueEmpty(queue)) {
        Dequeue(queue);
    }
    free(queue);
}

bool QueueEmpty(Queue* queue) {
    assert(queue);
    return queue->front == NULL;
}